﻿using System.Collections.Generic;
using DataScripter.Containers;
using DataScripter.Database;
using DataScripter.Scripting.Filters;
using DataScripter.Scripting.ScriptDefinitions;

namespace DataScripter.Scripting.Fluent
{
    public class FluentTableScriptRequest : IFluentTableScriptRequest
    {
        public IScriptDefinition ScriptDefinition { get; private set; }

        public FluentTableScriptRequest(IScriptDefinition scriptDefinition, ITableScriptRequest tableScriptRequest, IContainer container)
        {
            ScriptDefinition = scriptDefinition;
            Request = tableScriptRequest;
            Container = container;
        }

        public IFluentTableScriptRequest IncludeDependencies()
        {
            return IncludeDependencies(Request.TableStructure.ForeignKeys);
        }

        public IFluentTableScriptRequest IncludeDependencies(IEnumerable<IForeignKey> foreignKeys)
        {
            foreach (IForeignKey foreignKey in foreignKeys)
            {
                ScriptDefinition.RequestScript(foreignKey.ReferencedTableName);
            }
            return this;
        }

        public IFluentTableScriptRequest Where(string whereClause)
        {
            Request.Filters.Add("WHERE", new WhereFilter(whereClause));
            return this;
        }

        public ITableScriptRequest Request { get; private set; }
        public IContainer Container { get; set; }

        public IFluentTableScriptRequest FilterByForeignKey(IForeignKey foreignKey)
        {
            Request.Filters.Add(foreignKey.Name, new ForeignKeyFilter(foreignKey, Request, ScriptDefinition));
            return this;
        }

        public IFluentOrFilterRequest BeginOr()
        {
            return new FluentOrFilterRequest(this);
        }

        public IFluentTableScriptRequest Lookup(string fieldName, string lookupTable, string lookupField)
        {
            Request.SpecialFieldTreatments.Add(fieldName, new SpecialFieldTreatment(Container, Request, fieldName, lookupTable, lookupField));
            return this;
        }
    }
}
